/**
 * Created by Mic on 16/2/22.
 */

var Character = require('./character');
var util = require('util');
var logger = require('pomelo-logger').getLogger(__filename);
var _ = require('underscore');
var consts = require('../../consts/consts');
var DDZRule = require('../poker/rule');
var Robot = require('./robot');
var pomelo = require('pomelo');

var Player = function (seatIndex, info, desk) {
    Character.call(this, seatIndex, info);
    this.status = consts.Player.Status.Normal;
    this.deskClient = desk;
};

util.inherits(Player, Character);
module.exports = Player;

var handler = Player.prototype;

handler.ready = function (value) {
    this.deskClient.readyResult(this.seatIndex, value);
    this.setBeishu(value);
    this.readyStatus = value;
    console.warn(this.userName + ' 玩家状态 ' + this.status);
    this.setStatus(consts.Player.Status.Normal);
};
handler.jiao = function () {
};
handler.qiang = function () {

};
handler.notifyDizhu = function (dipai) {
    this.dizhu = true;
    this.addCards(dipai);
};
handler.double = function () {
    var self = this;
    this.timing = setTimeout(function () {
        self.autoDouble();
    }, 1000 * 10);
};
handler.notifyDouble = function (value) {
    if (!!this.timing) {
        clearTimeout(this.timing);
    }
    this.setDoubleStatus(value);
};
handler.notifyPlay = function (index, ondesk, remainsArr, dizhu, pass, remains) {
    var self = this;
    if (this.status == consts.Player.Status.Hosting) {
        this._robot.cards = this.cards;
        //this._robot.notifyPlay(index, ondesk, remainsArr, dizhu, pass, remains);
        //改成了托管只要可以不出就不出了
        this.timing = setTimeout(function () {
            self.autoPlay(index, ondesk, remainsArr.dizhu, pass, remains);
        }, 1000);
    } else if (this.status == consts.Player.Status.Disconnect) {
        this.timing = setTimeout(function () {
            self.autoPlay(index, ondesk, remainsArr.dizhu, pass, remains);
        }, 1000);
    }
};

//判断输赢
handler.getWinStatus = function (winIndex) {
    var winStatus = false;
    if (this.dizhu && (winIndex == consts.Desk.Code.Dizhu_win)) {
        winStatus = true;
    } else if (!this.dizhu && (winIndex == consts.Desk.Code.Farmer_win)) {
        winStatus = true;
    }
    return winStatus;
};

handler.getGameCoins = function (winIndex, dizhuIndex, deskBeishu, playerBeishu, baseBet) {
    var winStatus = this.getWinStatus(winIndex);
    var gameCoinArr = [];
    var gameCoin = 0;
    _.each(playerBeishu, function (p) {
        gameCoinArr.push(baseBet * deskBeishu * p);
    });

    if (this.dizhu) {
        gameCoinArr.splice(dizhuIndex, 1);
        gameCoin = (winStatus ? 1 : -1) * (gameCoinArr[0] + gameCoinArr[1]);
    } else {
        gameCoin = (winStatus ? 1 : -1) * gameCoinArr[this.seatIndex];
    }

    //判断赢的话赢的钱是否超过自身的钱
    var overtake = false;
    if (gameCoin > this.money) {
        overtake = true;
        gameCoin = this.money;
    }

    //在这里判断下金币是否够的
    if (gameCoin < 0 && (this.getMoney() + gameCoin) < 0) {
        //说明金币不够,只能扣除所有的
        gameCoin = -this.money;
        return {enough: false, gameCoin: gameCoin, beishu: this.getBeishu(), overtake: overtake};
    }
    //说明金币足够不用管
    return {enough: true, gameCoin: gameCoin, beishu: this.getBeishu(), overtake: overtake};

};
//托管
handler.hosting = function () {
    console.warn(this.userName + ' 托管了');
    this.setStatus(consts.Player.Status.Hosting);
    //托管
    this._robot = this.initHosting();

};
handler.unHosting = function () {
    this.setStatus(consts.Player.Status.Normal);
    if (!this._robot)return;
    this.playRound = this._robot.playRound;

    this._robot = null;
};

//掉线
handler.disconnect = function () {
    logger.fatal(this.userName + '掉线了,机器人代打! ' + this.seatIndex);
    //console.warn(this.userId,this.scode);
    this.setStatus(consts.Player.Status.Disconnect);
};
//连上了
handler.connect = function () {
    logger.fatal(this.userName + '重连上了 ');
    //console.warn(this.userId,this.scode);
    this.setStatus(consts.Player.Status.Normal);
    if (!!this._robot) {
        this.deskClient.unHosting({uuid: this.uuid});
    }
};
//托管功能
handler.initHosting = function () {
    var info = {

        headUrl: this.headUrl,
        uuid: this.uuid,
        userName: this.userName,
        deskName: this.deskName,
        roomName: this.roomName,
        money: this.money
    };
    var robot = new Robot(this.seatIndex, info, this.deskClient);
    robot.cards = this.cards;
    robot.dizhu = this.dizhu;
    robot.playRound = this.playRound;
    robot.robotTime = true;

    return robot;
};
// 超时处理              time out
handler.autoJiao = function () {
    this.deskClient.jiaoResult(this.seatIndex, false);
};
handler.autoQiang = function () {
    this.deskClient.qiangResult(this.seatIndex, false);
};
handler.autoDouble = function () {
    this.deskClient.doubleResult(this.seatIndex, false);
};

handler.autoPlay = function (index, ondesk, remainsArr, dizhu, pass, remains) {
    if (!this._robot) {
        //this.hosting();
        console.log('托管吧 ');
        this.deskClient.hosting({uuid: this.uuid});
    }
    var card = [];
    var cards = DDZRule.sort(this.cards);
    if (ondesk == null || ondesk.length == 0) {
        console.warn(index + '必须出' + cards);
        card.push(_.last(cards));
    }
    this.deskClient.playResult(index, card);
};

//                 setter and getter
handler.setDoubleStatus = function (value) {
    this.doubleStatus = value;
    this.setBeishu(value ? 2 : 1);
};
handler.getDoubleStatus = function () {
    return this.doubleStatus;
};
handler.setStatus = function (value) {
    this.status = value;
};
handler.getStatus = function () {
    return this.status;
};
handler.setBeishu = function (value) {
    this.beishu *= value;
};
handler.getBeishu = function () {
    return this.beishu;
};
//得到playRound 回合数
handler.getPlayRound = function () {
    return this.playRound;
};
handler.setPlayRound = function () {
    this.playRound++;
};
//设置不能抢地主 因为不叫了
handler.setCantQiang = function (value) {
    this.pointStatus = value;
};
//返回是否能抢地主 return true = 不能 false = 能
handler.getCantQiang = function () {
    return this.pointStatus;
};
//设置money
handler.setMoney = function (money) {
    this.money += Number(money);
    if (this.money < 0) {
        this.money = 0;
    }
    var playerInfo = this.baseInfo();
    var self = this;
    logger.info('更新玩家money ' + self.money);
    //userDao.updateMoney(playerInfo,this.money,function(err,res){
    console.log("更新金币 ", this.userId, this.scode);
    /////////////////for test
    this.deskClient.test(this.userName, this.userId, this.scode);

    pomelo.app.rpc.interface.interfaceRemote.updateMoney(null, this.userId, this.scode, money, function (err, res) {
        logger.info('更新完毕!');
        if (self.money < consts.Player.Money) {
            //通知领取救济金
            //logger.fatal('领取救济金啊 ' + self.money);
            pomelo.app.rpc.hall.hallRemote.helpMoney(null, playerInfo, function (data) {
                //logger.fatal('领取救济金完毕! ', data);
                if (data.code == 200 || data.isSuccess) {
                    self.money = data.money;
                }
            });
        }
    });
};
handler.getMoney = function () {
    return this.money;
};
//牌的处理
handler.addCards = function (card) {
    //这个时候是把桌子信息存入mem的最好时机
    pomelo.app.rpc.room.deskRemote.setDeskMem({serverId: this.deskClient.serverId},
        this.uuid, this.deskName, function (data) {
            logger.fatal('已经把desk 存入mem ' + data);
        });

    var cards = this.cards.slice(0);
    this.cards = [];
    this.cards = _.union(cards, card);
    return this.cards;
};
handler.getCards = function () {
    return this.cards;
};
handler.takeAwayCards = function (card) {
    if (card == null || card.length == 0)
        return this.cards;
    this.setPlayRound();
    var cards = this.cards.slice(0);
    this.cards = [];
    this.cards = _.difference(cards, card);
    return this.cards;
};
